﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.Business.Constants;
using StoreTransport.Business.Helper;
using StoreTransport.Business.Services;
using StoreTransport.DAO;
using StoreTransport.Data;
using StoreTransport.Resources;
using StoreTransport.DTO;

namespace StoreTransport.Presentation.Forms {
    public partial class StoreTransportReportForm : Form {
        private DataTable _allocationReportData = null;
        private DataTable _allocationResultData = null;
        private DataTable _orderReportData = null;
        private DataTable _transportReportData = null;
        private DataTable _transportResultData = null;
        private const string StoreTSTabName = "_tabStoreTransport";
        private const string CheckStoreTSTabName = "_tabCheckStoreTSSellDays";
        private const string MarketTSTabName = "_tabMarketTransport";
        private const string CheckStoreTMarketSTabName = "_tabCheckMarketTSSellDays";
        private const string OrderProductTabName = "_tabProductOrder";
        int _productlineID = 0;
        private ReportType _reportType;
        private ProductLine selectedPL;
        private Dictionary<string, int> _reportStoreTSNumber = new Dictionary<string, int>();
        // chua so luong chuyen phan bo di theo tung ma code, sau do dung dic nay update lai cho bang ProductOrder
        private Dictionary<int, int> _orderProductsNumber = new Dictionary<int, int>();
        private Dictionary<string, int> _reportMarketTSNumber = new Dictionary<string, int>();
        private IAllocatedService allocatedService = new AllocatedService();
        private ITransportService transportService = new TransportService();

        public StoreTransportReportForm() {
            InitializeComponent();
            _tabControl.TabPages.Clear();
        }

        public StoreTransportReportForm(int productLineID) {
            InitializeComponent();
            _tabControl.TabPages.Clear();
            _productlineID = productLineID;
            CommonHelper.ShowTabPage(_tabControl, _tabProductOrder);
            StoreTransportDataContext context = CommonHelper.GetContext();
            BuildOrderReportTable(context, context.ProductLines.Where(c => c.ID == productLineID).First());
            FillOrderReportData();
        }

        private void StoreTransportReportForm_Load(object sender, EventArgs e) {
            CheckOrderProducts();
            InitRegionTreeview();
            StoreTransportDataContext context = CommonHelper.GetContext();
            _drpProductLine.DisplayMember = ColumnName.ProductLineName;
            _drpProductLine.ValueMember = ColumnName.ID;
            _drpProductLine.DataSource = context.ProductLines.OrderBy(c => c.ProductLineName);
            if (_productlineID != 0) {
                _drpProductLine.SelectedValue = _productlineID;
            }
            _drpProductLine.Select();
        }

        private void CheckOrderProducts() {
            Form mdiForm = this.MdiParent;
            MenuStrip MainMenuStrip = mdiForm.MainMenuStrip;
            ToolStripMenuItem menuProductOrder = null;
            foreach (ToolStripMenuItem menu in MainMenuStrip.Items) {
                if (menu.Name == "menuProductOrder") {
                    menuProductOrder = menu;
                    break;
                }
            }
            if (menuProductOrder != null) {
                foreach (ToolStripMenuItem menu in menuProductOrder.DropDownItems) {
                    int productLineiId = int.Parse(menu.Name);
                    if (CommonHelper.IsWarningProductOrder(productLineiId)) {
                        menuProductOrder.ForeColor = Color.Red;
                        menu.ForeColor = Color.Red;
                    }
                }
            }
        }

        private void UpdateLastImportInfo() {
            DateTime lastUpdateDate = (_drpProductLine.SelectedItem as ProductLine).LastUpdatedDate;
            if (lastUpdateDate != DateTime.MinValue) {
                _lblImportDate.Text = lastUpdateDate.ToShortDateString();
            } else {
                _lblImportDate.Text = StoreTransportResource.Message_ProductLineDataNotFound;
            }
        }
        
        private void _btxShowReport_Click(object sender, EventArgs e) {
            Cursor.Current = Cursors.WaitCursor;
            ProductLine pl = (ProductLine)_drpProductLine.SelectedItem;
            CommonHelper.InitCalculateRelatedData(pl.ID);
            ResetGridView();
            if (_reportType != GetReportType()) {
                ShowTabs();
            }
            _reportStoreTSNumber.Clear();
            _reportMarketTSNumber.Clear();
            _orderProductsNumber.Clear();
            _reportType = GetReportType();
            StoreTransportDataContext context = CommonHelper.GetContext();
            if (!CommonHelper.IsValidDataToExport()) {
                MessageBox.Show(StoreTransportResource.ErrorMessage_InvalidInputToExport);
                return;
            }
            List<int> RegionIds = new List<int>();
            foreach (TreeNode node in _tvwRegion.Nodes) {
                if (node.Checked) {
                    RegionIds.Add(Convert.ToInt32(node.Name));
                }
            }


            // checking to load dât will be implement later because last compute date in productline
            // can not store 2 compute date ò Store and transport
            //  ProductLine pl = context.ProductLines.Where(line => line.ID == productLine.ID).Single();
            List<MarketData> markets = new List<MarketData>();
            TransportResultDto resultTransport = new TransportResultDto();
            switch (_reportType) {
                case ReportType.StoreTS:
                    markets = allocatedService.AllocateStore(context, pl, RegionIds, resultTransport.transports);
                    BuildAllocationReport(context, pl, markets);
                    BuildOrderReportTable(context, pl);
                    FillStoreReportData();
                    break;
                case ReportType.MarketTS:
                    resultTransport = transportService.BalanceProductBetweenMarkets(pl, RegionIds, context, markets);
                    BuildTransportDataTable(resultTransport, pl);
                    FillMarketReportData();
                    break;
                case ReportType.StoreMakertTS:
                    markets = allocatedService.AllocateStore(context, pl, RegionIds, resultTransport.transports);
                    BuildAllocationReport(context, pl, markets);
                    resultTransport = transportService.BalanceProductBetweenMarkets(pl, RegionIds, context, markets);
                    BuildTransportDataTable(resultTransport, pl);
                    BuildOrderReportTable(context, pl);
                    FillStoreReportData();
                    break;
                case ReportType.MarketStoreTS:
                    resultTransport = transportService.BalanceProductBetweenMarkets(pl, RegionIds, context, markets);
                    BuildTransportDataTable(resultTransport, pl);
                    markets = allocatedService.AllocateStore(context, pl, RegionIds, resultTransport.transports);
                    BuildAllocationReport(context, pl, markets);
                    BuildOrderReportTable(context, pl);
                    FillMarketReportData();
                    break;
            }
            Cursor.Current = Cursors.Default;
        }

        private void BuildTransportDataTable(TransportResultDto TransportReport, ProductLine pl) {
            if (TransportReport != null && TransportReport.transports.Count > 0) {
                _transportReportData = new DataTable();
                _transportReportData.Columns.Add(StoreTransportResource.ProductCode);
                _transportReportData.Columns.Add(StoreTransportResource.ProductName);
                _transportReportData.Columns.Add(StoreTransportResource.RegionName);
                _transportReportData.Columns.Add(StoreTransportResource.AreaName);
                _transportReportData.Columns.Add(StoreTransportResource.ProductKind_Col);
                _transportReportData.Columns.Add(StoreTransportResource.FromMarket);
                _transportReportData.Columns.Add(StoreTransportResource.ToMarket);
                _transportReportData.Columns.Add(StoreTransportResource.QuantityTransport);

                foreach (TransportData data in TransportReport.transports) {
                    DataRow row = _transportReportData.NewRow();
                    int col = 0;
                    row[col++] = data.productCode;
                    row[col++] = data.productName;
                    row[col++] = data.regionName;
                    row[col++] = data.areaName;
                    row[col++] = data.productKindName;
                    row[col++] = data.marketNameFrom;
                    row[col++] = data.marketNameTo;
                    row[col++] = data.numberTransport;
                    _transportReportData.Rows.Add(row);
                    // Build ReportHistory
                    if (!_reportMarketTSNumber.ContainsKey(data.productKindName)) {
                        _reportMarketTSNumber.Add(data.productKindName, 0);
                    }
                    _reportMarketTSNumber[data.productKindName] += data.numberTransport;
                }
            }
            BuildDataTableResult(TransportReport.markets, pl, false);
        }

        private void _btnExportReport_Click(object sender, EventArgs e) {
            // New FolderBrowserDialog instance
            Cursor.Current = Cursors.WaitCursor;
            string chosenFolder = Application.StartupPath;
            FolderBrowserDialog Fld = new FolderBrowserDialog();
            // Set initial selected folder
            Fld.SelectedPath = chosenFolder;
            // Show the "Make new folder" button
            Fld.ShowNewFolderButton = true;
            if (Fld.ShowDialog() == DialogResult.OK) {
                // Select successful
                chosenFolder = Fld.SelectedPath;
            } else {
                return;
            }
            _lblWaitingMessage.Text = StoreTransportResource.Message_Exporting;
            _lblWaitingMessage.Visible = true;
            //_data.Columns.Remove(ColumnName.ID);

            string tabName = _tabControl.SelectedTab.Name;
            DataTable exportTable = null;
            string exportFileName = string.Empty;
            bool showHeader = false;
            switch (tabName) {
                case StoreTSTabName: {
                        exportFileName = StoreTransportResource.StoreExportFileParten;
                        exportTable = CommonHelper.FlipDataTable(_allocationReportData);
                        exportTable = CommonHelper.RemoveEmptyData(exportTable, 3);
                        break;
                    }
                case CheckStoreTSTabName: {
                        exportTable = _allocationResultData;
                        exportFileName = StoreTransportResource.StoreResultExportFileParten;
                        showHeader = true;
                        break;
                    }
                case MarketTSTabName: {
                        exportTable = _transportReportData;
                        exportFileName = StoreTransportResource.MarketExportFileParten;
                        showHeader = true;
                        break;
                    }
                case CheckStoreTMarketSTabName: {
                        exportTable = _transportResultData;
                        exportFileName = StoreTransportResource.MarketResultExportFileParten;
                        showHeader = true;
                        break;
                    }
                case OrderProductTabName: {
                        exportTable = _orderReportData;
                        exportFileName = StoreTransportResource.OrderExportFileParten;
                        showHeader = true;
                        break;
                    }
                default:
                    break;
            }
            //DataTable fliipTale = CommonHelper.FlipDataTable(_dataTable1);
            if (exportTable == null) {
                MessageBox.Show(StoreTransportResource.ErrorMessage_NoDataToExport);
                return;
            }
            string message = ExcelHelper.ExportData(exportTable, showHeader, chosenFolder, exportFileName);
            _lblWaitingMessage.Visible = false;
            if (!string.IsNullOrEmpty(message)) {
                MessageBox.Show(message);
            } else {
                MessageBox.Show(StoreTransportResource.Message_ExportingFinihed);
            }
            // update data in ProductOrderReport
            //UpdateProductOrder();
            StoreUserHistory(selectedPL);
            Cursor.Current = Cursors.Default;
        }

        private void UpdateProductOrder() {
            StoreTransportDataContext context = CommonHelper.GetContext();
            var productOrders = context.ProductOrders.Where(c => c.ProductLineId == selectedPL.ID);
            foreach (var order in productOrders) {
                if (_orderProductsNumber.ContainsKey(order.ProductId)) {
                    order.ComputedInventory = order.ImportInventory - _orderProductsNumber[order.ProductId];
                } else {
                    // reset value
                    order.ComputedInventory = order.ImportInventory;
                }
            }
            context.SubmitChanges();
            CheckOrderProducts();
        }

        private void StoreUserHistory(ProductLine pl) {
            StoreTransportDataContext context = CommonHelper.GetContext();
            User user = (this.MdiParent as MDIMainForm).user;
            if (user == null) {
                return;
            }
            Guid gui = Guid.NewGuid();
            foreach (var total in _reportStoreTSNumber) {
                ReportHistory uh = new ReportHistory();
                // guid set to know this these item belong to thic export time.
                uh.Description = gui.ToString();
                uh.Name = user.Name;
                uh.Username = user.Username;
                uh.ProductLineName = pl.ProductLineName;
                uh.ProductKindName = total.Key;
                uh.StoreTSNumber = total.Value;
                uh.ReportType = CommonConstant.ReportType[ReportType.StoreTS.ToString()];
                uh.ReportDate = DateTime.Now;
                context.ReportHistories.InsertOnSubmit(uh);
            }

            gui = Guid.NewGuid();
            foreach (var total in _reportMarketTSNumber) {
                ReportHistory uh = new ReportHistory();
                // guid set to know this these item belong to thic export time.
                uh.Description = gui.ToString();
                uh.Name = user.Name;
                uh.Username = user.Username;
                uh.ProductLineName = pl.ProductLineName;
                uh.ProductKindName = total.Key;
                uh.StoreTSNumber = total.Value;
                uh.ReportType = CommonConstant.ReportType[ReportType.MarketTS.ToString()];
                uh.ReportDate = DateTime.Now;
                context.ReportHistories.InsertOnSubmit(uh);
            }
            try {
                context.SubmitChanges();
            } catch (Exception ex) {
                // export
            }
        }

        private void InitRegionTreeview() {
            StoreTransportDataContext context = CommonHelper.GetContext();
            var regionList = context.Regions.OrderBy(c => c.RegionName);
            foreach (var region in regionList) {
                _tvwRegion.Nodes.Add(region.ID.ToString(), region.RegionName);
                _tvwRegion.Nodes[_tvwRegion.Nodes.Count - 1].Checked = true;
            }
        }

        private void _drpProductLine_SelectedIndexChanged(object sender, EventArgs e) {
            StoreTransportDataContext context = CommonHelper.GetContext();
            ProductLine pl = (ProductLine)_drpProductLine.SelectedItem;
            selectedPL = pl;
            UpdateLastImportInfo();
        }

        private void BuildOrderReportTable(StoreTransportDataContext context, ProductLine pl) {
            List<ProductOrderDTO> orderProduct = ProductOrderService.BuildProductOrdersList(pl.ID);
            if (orderProduct == null || orderProduct.Count == 0) {
                return;
            }
            _orderReportData = new DataTable();
            _orderReportData.Columns.Add(StoreTransportResource.ProductKind_Col);
            _orderReportData.Columns.Add(StoreTransportResource.SumInventory);
            _orderReportData.Columns.Add(StoreTransportResource.SumInvetoryAfter);
            _orderReportData.Columns.Add(StoreTransportResource.SumSaleRate);
            _orderReportData.Columns.Add(StoreTransportResource.ProductRecieveNumber);
            _orderReportData.Columns.Add(StoreTransportResource.LastestOrderDate);
            _orderReportData.Columns.Add(StoreTransportResource.OrderNumber);
            foreach (var order in orderProduct) {
                if (order.SumSaleRate > 0) {
                    int col = 0;
                    DataRow row = _orderReportData.NewRow();
                    row[col++] = order.ProductKindName;
                    row[col++] = order.SumInventoryNumber;
                    row[col++] = order.SumComputedNumber;
                    row[col++] = order.SumSaleRate;
                    row[col++] = order.NumberRecieveProduct;
                    row[col++] = order.WarningDate.ToShortDateString();
                    row[col++] = CommonHelper.RoundedByPackage(order.OrderQuantity, pl.Package);
                    _orderReportData.Rows.Add(row);
                }
            }
            _grvdOrderView.DataSource = _orderReportData;
        }

        public void BuildDataTableResult(List<MarketData> markets, ProductLine pl, bool isAllocation) {
            List<int> columnNames = pl.ProductKinds.Select(pk => pk.ID).ToList();
            DataTable datatable = new DataTable();
            int col = 0;
            //DataRow rowInfo = _dataTable2.NewRow();
            datatable.Columns.Add(StoreTransportResource.Market_MarketName);
            datatable.Columns.Add(StoreTransportResource.RegionName);
            datatable.Columns.Add(StoreTransportResource.AreaName);
            string before = isAllocation ? StoreTransportResource.Before_Allocation : StoreTransportResource.BeforeTransport;
            string after = isAllocation ? StoreTransportResource.After_Allocation : StoreTransportResource.AfterTransport;
            string quatityName = isAllocation ? StoreTransportResource.QuantityStoreTransport : StoreTransportResource.QuantityMarketTransport;
            foreach (int id in columnNames) {
                string ProductKindName = CommonHelper.ProductKindList[id].ProductKindName;
                datatable.Columns.Add(ProductKindName + "\r\n" + StoreTransportResource.QuantityTransport + before, typeof(int));
                datatable.Columns.Add(ProductKindName + "\r\n" + StoreTransportResource.SumSaleRate);
                datatable.Columns.Add(ProductKindName + "\r\n" + StoreTransportResource.QuantityTransport);
                datatable.Columns.Add(ProductKindName + "\r\n" + StoreTransportResource.QuantityTransport + after, typeof(int));
            }
            foreach (MarketData market in markets) {
                DataRow rowInfo1 = datatable.NewRow();
                col = 0;
                rowInfo1[col++] = market.MarketName;
                rowInfo1[col++] = market.RegionName;
                rowInfo1[col++] = market.AreaName;
                bool isAdd = false;
                foreach (int ProductKindId in columnNames) {
                    int value1 = 0;
                    int value2 = 0;
                    double sale = 0;
                    int amount = 0;
                    if (market.DicProductKinds.ContainsKey(ProductKindId)) {
                        ProductKindData productKind = market.DicProductKinds[ProductKindId];
                        if (productKind.SaleRate > 0) {
                            sale = productKind.SaleRate;
                            amount = productKind.Amount;
                            value1 = Convert.ToInt32(productKind.ImportInventory);
                            value2 = Convert.ToInt32(productKind.ImportInventory + amount);
                        }
                    }
                    rowInfo1[col++] = value1;
                    rowInfo1[col++] = sale;
                    rowInfo1[col++] = amount;
                    rowInfo1[col++] = value2;
                    if (value1 > 0 || value2 > 0) {
                        isAdd = true;
                    }
                }
                if (isAdd) {
                    datatable.Rows.Add(rowInfo1);
                }
            }
            if (isAllocation) {
                _allocationResultData = datatable;
            } else {
                _transportResultData = datatable;
            }
        }

        private void BuildAllocationReport(StoreTransportDataContext context, ProductLine pl, List<MarketData> markets) {
            List<ProductOrder> headerData = context.ProductOrders.Where(ro => pl.ID == ro.ProductLineId && (
                ro.SumSaleRate > 0 || ro.ImportInventory > 0))
                .OrderBy(ro => ro.ProductKindId).ToList();
            _allocationReportData = new DataTable();

            int col = 0;
            _allocationReportData.Columns.Add(StoreTransportResource.ProductCode);
            DataRow productNameRow = _allocationReportData.NewRow();
            DataRow kindNameRow = _allocationReportData.NewRow();
            kindNameRow[col] = StoreTransportResource.ProductKind_Col;
            productNameRow[col] = StoreTransportResource.ProductName;
            col++;
            foreach (var header in headerData) {
                Product p = CommonHelper.ProductList[header.ProductId];
                ProductKind k = CommonHelper.ProductKindList[header.ProductKindId];
                _allocationReportData.Columns.Add(p.ProductCode);
                kindNameRow[col] = k.ProductKindName;
                productNameRow[col] = p.ProductName;
                col++;
            }
            _allocationReportData.Rows.Add(kindNameRow);
            _allocationReportData.Rows.Add(productNameRow);
            foreach (MarketData m in markets) {
                DataRow row = _allocationReportData.NewRow();
                bool isShow = true;
                col = 0;
                row[col] = m.MarketName;
                foreach (var header in headerData) {
                    col++;
                    if (!m.DicProductKinds.ContainsKey(header.ProductKindId)) {
                        continue;
                    }
                    ProductKindData pKind = m.DicProductKinds[header.ProductKindId];
                    string value = string.Empty;
                    if (pKind.DicProducts.ContainsKey(header.ProductId)) {
                        ProductData p = pKind.DicProducts[header.ProductId];
                        if (p.Amount > 0) {
                            value = "" + p.Amount;
                            //isShow = true;

                            // build product Order
                            if (!_orderProductsNumber.ContainsKey(header.ProductId)) {
                                _orderProductsNumber.Add(header.ProductId, 0);
                            }
                            _orderProductsNumber[header.ProductId] += p.Amount;

                            // Build ReportHistory
                            if (!_reportStoreTSNumber.ContainsKey(pKind.ProductKindName)) {
                                _reportStoreTSNumber.Add(pKind.ProductKindName, 0);
                            }
                            _reportStoreTSNumber[pKind.ProductKindName] += p.Amount;
                        }
                    }
                    row[col] = value;
                }
                if (isShow) {
                    _allocationReportData.Rows.Add(row);
                }
            }
            UpdateProductOrder();
            BuildDataTableResult(markets, pl, true);
        }

        private void ShowTabs() {
            _tabControl.TabPages.Clear();
            ReportType type = GetReportType();
            if (type == ReportType.StoreTS) {
                CommonHelper.ShowTabPage(_tabControl, _tabStoreTransport);
                CommonHelper.ShowTabPage(_tabControl, _tabCheckStoreTSSellDays);
                CommonHelper.ShowTabPage(_tabControl, _tabProductOrder);
            } else if (type == ReportType.MarketTS) {
                CommonHelper.ShowTabPage(_tabControl, _tabMarketTransport);
                CommonHelper.ShowTabPage(_tabControl, _tabCheckMarketTSSellDays);
            } else if (type == ReportType.StoreMakertTS) {
                CommonHelper.ShowTabPage(_tabControl, _tabStoreTransport);
                CommonHelper.ShowTabPage(_tabControl, _tabCheckStoreTSSellDays);
                CommonHelper.ShowTabPage(_tabControl, _tabMarketTransport);
                CommonHelper.ShowTabPage(_tabControl, _tabCheckMarketTSSellDays);
                CommonHelper.ShowTabPage(_tabControl, _tabProductOrder);
            } else {
                CommonHelper.ShowTabPage(_tabControl, _tabMarketTransport);
                CommonHelper.ShowTabPage(_tabControl, _tabCheckMarketTSSellDays);
                CommonHelper.ShowTabPage(_tabControl, _tabStoreTransport);
                CommonHelper.ShowTabPage(_tabControl, _tabCheckStoreTSSellDays);
                CommonHelper.ShowTabPage(_tabControl, _tabProductOrder);
            }
            _tabControl.SelectedIndex = 0;
        }

        private ReportType GetReportType() {
            if (_radStoreTS.Checked) {
                return ReportType.StoreTS;
            } else if (_radMarketTS.Checked) {
                return ReportType.MarketTS;
            } else if (_radStoreMarketTS.Checked) {
                return ReportType.StoreMakertTS;
            } else {
                return ReportType.MarketStoreTS;
            }
        }

        private void _btxBrowseFile_Click(object sender, EventArgs e) {
            var FD = new System.Windows.Forms.OpenFileDialog();
            if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                _tbxImportFilePath.Text = FD.FileName;
            }
        }

        private void _btxImportData_Click(object sender, EventArgs e) {
            Cursor.Current = Cursors.WaitCursor;
            string errorMessage = CommonHelper.CheckRequiredField(_tbxImportFilePath.Text, _lblImportFilePath.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            if (!(_tbxImportFilePath.Text.ToLower().EndsWith(CommonConstant.ExcelFileExtendtion.ToLower()))) {
                errorMessage = Resources.StoreTransportResource.ErrorMessage_FilePathNotValid;
                MessageBox.Show(errorMessage);
                return;
            }
            _lblWaitingBox.Visible = true;
            ProductLine pl = (ProductLine)_drpProductLine.SelectedItem;
            bool success = ExcelHelper.ReadInputExcelFile(_tbxImportFilePath.Text, pl);
            _lblWaitingBox.Visible = false;
            Cursor.Current = Cursors.Default;
            if (success) {
                MessageBox.Show(StoreTransportResource.ImportFinishes);
                StoreTransportDataContext context = CommonHelper.GetContext();
                ProductLine newPl = context.ProductLines.Where(c => pl.ID == c.ID).First();
                newPl.LastUpdatedDate = DateTime.Today;
                context.SubmitChanges();
            } else {
                MessageBox.Show(StoreTransportResource.ImportFileFail);
            }
        }

        private void ResetGridView() {
            _grvdOrderView.DataSource = null;
            _grdMarketTransportResult.DataSource = null;
            _grdMarketReport.DataSource = null;
            _grdReportSellDays.DataSource = null;
            _grdStoreReport.DataSource = null;
        }

        private void FillDataToGrid() {
            if (_tabControl.SelectedTab == null) {
                return;
            }
            string tabName = _tabControl.SelectedTab.Name;
            Cursor.Current = Cursors.WaitCursor;
            switch (tabName) {
                case StoreTSTabName: {
                        FillStoreReportData();
                        break;
                    }
                case CheckStoreTSTabName: {
                        FillStoreResultData();
                        break;
                    }
                case MarketTSTabName: {
                        FillMarketReportData();
                        break;
                    }
                case CheckStoreTMarketSTabName: {
                        FillMarketResultData();
                        break;
                    }
                case OrderProductTabName: {
                        FillOrderReportData();
                        break;
                    }
                default:
                    break;
            }
            Cursor.Current = Cursors.Default;
        }

        private void FillOrderReportData() {
            if (_orderReportData != null && _grvdOrderView.DataSource == null) {
                _grvdOrderView.DataSource = _orderReportData;
            }
        }

        private void FillMarketResultData() {
            if (_transportResultData != null && _transportResultData.Rows.Count > 0 &&
                    _grdMarketTransportResult.DataSource == null) {
                _grdMarketTransportResult.DataSource = _transportResultData;
                _grdMarketTransportResult.Columns[2].Frozen = true;
                FillColor(2, _grdMarketTransportResult);
                _grdMarketTransportResult.DoubleBuffered(true);
            }
        }

        private void FillMarketReportData() {
            if (_transportReportData != null && _transportReportData.Rows.Count > 0 &&
                    _grdMarketReport.DataSource == null) {
                _grdMarketReport.DataSource = _transportReportData;
                _grdMarketReport.DoubleBuffered(true);
            }
        }

        private void FillStoreResultData() {
            if (_allocationResultData != null && _allocationResultData.Rows.Count > 0 &&
                    _grdReportSellDays.DataSource == null) {
                _grdReportSellDays.DataSource = _allocationResultData;
                int metaColumn = 2;
                _grdReportSellDays.Columns[2].Frozen = true;
                FillColor(metaColumn, _grdReportSellDays);
                _grdReportSellDays.DoubleBuffered(true);
            }
        }

        private void FillColor(int metaColumn, DataGridView grid) {
            for (int i = metaColumn + 1; i + 3 < grid.ColumnCount; i = i + 4) {
                grid.Columns[i].DefaultCellStyle.ForeColor = Color.Red;
                grid.Columns[i + 3].DefaultCellStyle.ForeColor = Color.Green;
                if ((i - 3) % 8 < 4) {
                    Color bc = ColorTranslator.FromHtml("#E3E4FA");
                    grid.Columns[i].DefaultCellStyle.BackColor = bc;
                    grid.Columns[i + 1].DefaultCellStyle.BackColor = bc;
                    grid.Columns[i + 2].DefaultCellStyle.BackColor = bc;
                    grid.Columns[i + 3].DefaultCellStyle.BackColor = bc;
                }
            }
        }

        private void FillStoreReportData() {
            if (_allocationReportData != null && _allocationReportData.Rows.Count > 0 &&
                    _grdStoreReport.DataSource == null) {
                DataTable table = CommonHelper.RemoveEmptyData(_allocationReportData, 1);
                table = CommonHelper.FlipDataTable(table);
                table = CommonHelper.RemoveEmptyData(table, 3);
                if (table.Rows.Count > 0) {
                    _grdStoreReport.ColumnHeadersVisible = false;
                    _grdStoreReport.DataSource = table;
                    _grdStoreReport.Rows[0].Frozen = true;
                    _grdStoreReport.Columns[2].Frozen = true;
                    _grdStoreReport.DoubleBuffered(true);
                }
            }
        }

        private void _tabControl_Click(object sender, EventArgs e) {
            FillDataToGrid();
        }
    }
}
